package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.help.entity.*;
import com.campus.help.mapper.*;
import com.campus.help.service.DashboardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 仪表盘服务实现类
 *
 * @author campus-help
 * @since 2024-01-29
 */
@Slf4j
@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private LaborMapper laborMapper;

    @Autowired
    private LaborApplicationMapper laborApplicationMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private LaborTypeMapper laborTypeMapper;

    @Override
    public Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();

        try {
            // 学生总数
            Long totalStudents = studentMapper.selectCount(
                new LambdaQueryWrapper<Student>()
                    .eq(Student::getDeleted, 0)
            );

            // 任务总数
            Long totalTasks = laborMapper.selectCount(
                new LambdaQueryWrapper<Labor>()
                    .eq(Labor::getDeleted, 0)
            );

            // 待审核申请数
            Long pendingApplications = laborApplicationMapper.selectCount(
                new LambdaQueryWrapper<LaborApplication>()
                    .eq(LaborApplication::getStatus, "pending")
            );

            // 合作学校数
            Long totalSchools = schoolMapper.selectCount(
                new LambdaQueryWrapper<School>()
                    .eq(School::getDeleted, 0)
            );

            stats.put("totalStudents", totalStudents != null ? totalStudents : 0);
            stats.put("totalTasks", totalTasks != null ? totalTasks : 0);
            stats.put("pendingApplications", pendingApplications != null ? pendingApplications : 0);
            stats.put("totalSchools", totalSchools != null ? totalSchools : 0);

            log.info("获取仪表盘统计数据成功: {}", stats);
        } catch (Exception e) {
            log.error("获取仪表盘统计数据失败", e);
            // 返回默认值
            stats.put("totalStudents", 0);
            stats.put("totalTasks", 0);
            stats.put("pendingApplications", 0);
            stats.put("totalSchools", 0);
        }

        return stats;
    }

    @Override
    public List<Map<String, Object>> getRecentTasks(Integer limit) {
        List<Map<String, Object>> recentTasks = new ArrayList<>();

        try {
            // 查询最近的劳务任务
            List<Labor> labors = laborMapper.selectList(
                new LambdaQueryWrapper<Labor>()
                    .eq(Labor::getDeleted, 0)
                    .orderByDesc(Labor::getCreateTime)
                    .last("LIMIT " + limit)
            );

            for (Labor labor : labors) {
                Map<String, Object> task = new HashMap<>();
                task.put("id", labor.getId());
                task.put("title", labor.getJobTitle());
                task.put("type", "labor");
                task.put("status", labor.getStatus());
                task.put("createdAt", labor.getCreateTime());

                // 获取劳务类型名称
                if (labor.getTypeId() != null) {
                    LaborType laborType = laborTypeMapper.selectById(labor.getTypeId());
                    if (laborType != null) {
                        task.put("typeName", laborType.getTypeName());
                    }
                }

                recentTasks.add(task);
            }

            log.info("获取最近任务成功，数量: {}", recentTasks.size());
        } catch (Exception e) {
            log.error("获取最近任务失败", e);
        }

        return recentTasks;
    }

    @Override
    public List<Map<String, Object>> getNotifications(Integer limit) {
        List<Map<String, Object>> notifications = new ArrayList<>();

        try {
            // 模拟系统通知数据
            // 在实际项目中，这里应该从通知表中查询数据
            Map<String, Object> notification1 = new HashMap<>();
            notification1.put("id", 1);
            notification1.put("title", "系统维护通知");
            notification1.put("content", "系统将于今晚12点进行维护升级");
            notification1.put("isRead", false);
            notification1.put("createdAt", LocalDateTime.now().minusHours(1));

            Map<String, Object> notification2 = new HashMap<>();
            notification2.put("id", 2);
            notification2.put("title", "新功能上线");
            notification2.put("content", "劳务类型管理功能已上线");
            notification2.put("isRead", true);
            notification2.put("createdAt", LocalDateTime.now().minusHours(3));

            notifications.add(notification1);
            notifications.add(notification2);

            log.info("获取系统通知成功，数量: {}", notifications.size());
        } catch (Exception e) {
            log.error("获取系统通知失败", e);
        }

        return notifications;
    }

    @Override
    public List<Map<String, Object>> getTaskDistribution() {
        List<Map<String, Object>> distribution = new ArrayList<>();

        try {
            // 查询劳务类型分布
            List<LaborType> laborTypes = laborTypeMapper.selectList(
                new LambdaQueryWrapper<LaborType>()
                    .eq(LaborType::getDeleted, 0)
                    .eq(LaborType::getStatus, 1)
            );

            for (LaborType laborType : laborTypes) {
                Long count = laborMapper.selectCount(
                    new LambdaQueryWrapper<Labor>()
                        .eq(Labor::getTypeId, laborType.getId())
                        .eq(Labor::getDeleted, 0)
                );

                Map<String, Object> item = new HashMap<>();
                item.put("name", laborType.getTypeName());
                item.put("value", count != null ? count : 0);
                item.put("color", laborType.getColor());
                distribution.add(item);
            }

            log.info("获取任务分布成功，数量: {}", distribution.size());
        } catch (Exception e) {
            log.error("获取任务分布失败", e);
        }

        return distribution;
    }

    @Override
    public List<Map<String, Object>> getUserActivity(Integer days) {
        List<Map<String, Object>> activity = new ArrayList<>();

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

            // 生成最近N天的日期
            for (int i = days - 1; i >= 0; i--) {
                LocalDateTime date = LocalDateTime.now().minusDays(i);
                LocalDateTime dayStart = date.withHour(0).withMinute(0).withSecond(0);
                LocalDateTime dayEnd = date.withHour(23).withMinute(59).withSecond(59);

                // 统计当天新注册用户数
                Long newUsers = studentMapper.selectCount(
                    new LambdaQueryWrapper<Student>()
                        .between(Student::getCreateTime, dayStart, dayEnd)
                        .eq(Student::getDeleted, 0)
                );

                // 统计当天活跃用户数（发布或申请任务）
                Long activeUsers = laborMapper.selectCount(
                    new LambdaQueryWrapper<Labor>()
                        .between(Labor::getCreateTime, dayStart, dayEnd)
                        .eq(Labor::getDeleted, 0)
                );

                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", date.format(formatter));
                dayData.put("newUsers", newUsers != null ? newUsers : 0);
                dayData.put("activeUsers", activeUsers != null ? activeUsers : 0);
                activity.add(dayData);
            }

            log.info("获取用户活跃度成功，天数: {}", days);
        } catch (Exception e) {
            log.error("获取用户活跃度失败", e);
        }

        return activity;
    }
}
